package org.scala.javafx.diagnostics

import javafx.scene.Node
import javafx.beans.value.ObservableValue
import javafx.collections.ObservableList

import org.scala.javafx.rich.Enrich._
import scala.collection.JavaConverters._

case class SpyInfo(val name: String, val item: Object) {
  def value: Object = {
    item match {
      case null => null
      case observableValue: ObservableValue[Nothing] => observableValue.getValue()
      case x => x
    }
  }
  
  def itemString: String = {
    if (value == null) {
      "null"
    } else {
      value.toString()
    }
  }

  lazy val children = {
    var list: List[SpyInfo] = Nil
    
    if (this.value != null) {
      this.value match {
        case observableList: ObservableList[_] => {
          observableList.asInstanceOf[ObservableList[Object]].asScala.zipWithIndex.foreach { case (item, i) =>
            list = SpyInfo("[" + i + "]", item)::list
          }
        }
        case _ => {
          for ((name, observableList) <- this.value._observableLists.toList.sortBy(_._1)) {
            list = SpyInfo(name, observableList)::list
          }
    
          for ((name, property) <- this.value._properties.toList.sortBy(_._1)) {
            list = SpyInfo(name, property)::list
          }
        }
      }
    }
    
    list.reverse
  }
}
